<template>
  <t-popup expand-animation placement="bottom-right" trigger="click">
    <template #content>
      <div class="header-msg">
        <div class="header-msg-top">
          <p>消息通知</p>
          <t-button v-if="unreadMsg.length > 0" class="clear-btn" variant="text" theme="primary" @click="markAllAsRead"
            >全部已读</t-button
          >
        </div>
        <t-list v-if="unreadMsg.length > 0" class="narrow-scrollbar" :split="false">
          <t-list-item v-for="(item, index) in unreadMsg" :key="index">
            <div class="message-item">
              <div class="message-content">
                <p class="title">{{ item.title }}</p>
                <p class="content">{{ item.content }}</p>
                <p class="time">{{ formatTime(item.createTime) }}</p>
              </div>
              <div class="message-action">
                <t-button size="small" variant="outline" @click="handleMessage(item)">查看详情</t-button>
                <t-button size="small" variant="text" @click="markAsRead(item.id)">标记已读</t-button>
              </div>
            </div>
          </t-list-item>
        </t-list>
        <div v-else class="empty-list">
          <img src="https://tdesign.gtimg.com/pro-template/personal/nothing.png" alt="空" />
          <p>暂无消息</p>
        </div>
        <div v-if="unreadMsg.length > 0" class="header-msg-bottom">
          <t-button class="header-msg-bottom-link" variant="text" theme="default" block @click="goDetail">
            查看全部
          </t-button>
        </div>
      </div>
    </template>
    <t-badge :count="unreadCount" :offset="[4, 4]">
      <t-button theme="default" shape="square" variant="text">
        <t-icon name="notification" />
      </t-button>
    </t-badge>
  </t-popup>
</template>

<script setup lang="ts">
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { getLatestMessagesApi, getUnreadCountApi, markAllAsReadApi, markAsReadApi } from '@/api/message';
import { useUserStore } from '@/store';
import { formatTime } from '@/utils/format';

const user = useUserStore();

interface Message {
  id: number;
  type: string;
  title: string;
  content: string;
  businessId: number;
  createTime: string;
}

const router = useRouter();
const ws = ref<WebSocket | null>(null);
const unreadMsg = ref<Message[]>([]);
const unreadCount = ref(0);

// 连接WebSocket
const connectWebSocket = () => {
  ws.value = new WebSocket(`${import.meta.env.VITE_WEBSOCKET_URL}/message/ws?userId=${user.userInfo.id}`);

  ws.value.onopen = () => {
    console.log('WebSocket连接已建立');
  };

  ws.value.onmessage = (event) => {
    const message = JSON.parse(event.data);
    unreadMsg.value.unshift(message);
    showNotification(message);
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
};

// 显示系统通知
const showNotification = (message: Message) => {
  MessagePlugin.info({
    content: message.title,
    duration: 3000,
  });
};

// 处理消息点击
const handleMessage = (message: Message) => {
  markAsRead(message.id);
  switch (message.type) {
    case 'order':
      router.push(`/afterSales/order/index`);
      break;
    case 'after_sales':
      router.push(`/afterSales/feedback/index`);
      break;
    default:
      break;
  }
};

// 获取未读消息总数
const loadUnreadCount = async () => {
  try {
    const count = await getUnreadCountApi();
    unreadCount.value = count;
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 初始化加载消息
const loadMessages = async () => {
  try {
    const messages = await getLatestMessagesApi();
    unreadMsg.value = messages;
    await loadUnreadCount();
  } catch (error) {
    console.error('加载消息失败:', error);
  }
};

// 标记消息为已读
const markAsRead = async (messageId: number) => {
  try {
    await markAsReadApi(messageId);
    await loadMessages();
    await loadUnreadCount();
    MessagePlugin.success('标记消息已读成功');
  } catch (error) {
    console.error('标记消息已读失败:', error);
  }
};

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    await markAllAsReadApi();
    unreadMsg.value = [];
    unreadCount.value = 0;
    MessagePlugin.success('标记所有消息已读成功');
  } catch (error) {
    console.error('标记所有消息已读失败:', error);
  }
};

// 跳转到消息详情页
const goDetail = () => {
  router.push('/user/message');
};

onMounted(() => {
  loadMessages();
  connectWebSocket();
});

onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});
</script>

<style lang="less" scoped>
.header-msg {
  width: 400px;
  margin: calc(0px - var(--td-comp-paddingTB-xs)) calc(0px - var(--td-comp-paddingLR-s));

  .empty-list {
    text-align: center;
    padding: var(--td-comp-paddingTB-xxl) 0;
    font: var(--td-font-body-medium);
    color: var(--td-text-color-secondary);

    img {
      width: var(--td-comp-size-xxxxl);
    }

    p {
      margin-top: var(--td-comp-margin-xs);
    }
  }

  &-top {
    position: relative;
    font: var(--td-font-title-medium);
    color: var(--td-text-color-primary);
    text-align: left;
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl) 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .clear-btn {
      right: calc(var(--td-comp-paddingTB-l) - var(--td-comp-paddingLR-xl));
    }
  }

  &-bottom {
    align-items: center;
    display: flex;
    justify-content: center;
    padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-s);
    border-top: 1px solid var(--td-component-stroke);

    &-link {
      text-decoration: none;
      cursor: pointer;
      color: var(--td-text-color-placeholder);
    }
  }

  .t-list {
    padding: var(--td-comp-margin-s) var(--td-comp-margin-s);
  }

  .message-item {
    padding: 12px;

    .message-content {
      .title {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 4px;
      }

      .content {
        font-size: 13px;
        color: var(--td-text-color-secondary);
        margin-bottom: 4px;
      }

      .time {
        font-size: 12px;
        color: var(--td-text-color-placeholder);
      }
    }

    .message-action {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 8px;
    }

    &:hover {
      background-color: var(--td-bg-color-container-hover);
    }
  }
}
</style>
